//
//  FriendsViewController.m
//  Molian
//
//  Created by 胡津 on 15/3/16.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//
#define selfBadgeTag 200000

#import "FriendsViewController.h"

#include <ctype.h>
#include "Pinyin.h"
#import "FriendCell.h"
#import "SRRefreshView.h" //下拉刷新
#import "FriendApplyViewController.h"
#import "LikeMeViewController.h"
#import "MLUserDataViewController.h"
#define kSearchViewHeight 44

#define kNumber 300
@interface FriendsViewController ()<UITextFieldDelegate,SRRefreshDelegate>
{
    UIView *searchView;
    BOOL  isClick;
}
@property (nonatomic, strong)UITableView *tableView;

//@property (nonatomic, strong) NSArray *indexArray;

// 根据首字母分组后的好友字典
//@property (nonatomic, strong) NSMutableDictionary *groupedFriends;

// 专属恋人恋人列表
//@property (nonatomic, strong) NSMutableArray *recommendFriends;

//@property (nonatomic, strong) NSMutableArray *friendSectionTitles;
//@property (nonatomic, strong) CDPSearchController *searchController;
//@property (nonatomic, strong) AddUser *adduservc;

@property (strong, nonatomic) UITextField *searchTextField;

@property (nonatomic, strong)UITableView *searchTableView;

@property (nonatomic, strong)NSArray  *searchArr;//搜索数组
@property (nonatomic, strong)NSDictionary *searchDic;
@property (nonatomic, strong)NSArray *nFriendArr;//搜索到的数组
@property (nonatomic, strong)NSArray *friendArr;//试恋数组
//先用不好的算法以后再改进
@property (nonatomic)BOOL isSearchFriend;

@property (nonatomic, strong)UIButton *rightButton;//搜索框右侧

//下拉刷新
@property (strong, nonatomic) SRRefreshView *slimeView;


@end

@implementation FriendsViewController
{
    Utils * promptView;
    NSString *biaoshiStr;
}
#pragma mark - life cycle

-(void)cmd:(NSNotification *)notification
{
    NSDictionary *dic=[notification userInfo];
    EMMessage *message = [dic objectForKey:@"message"];
    if ([message.from isEqualToString:@"new_friend"]) {
        UIView *Badge = (UIView*)[self.view viewWithTag:selfBadgeTag+1];
        [Utils Hidden:Badge Bool:YES];
    }else if ([message.from isEqualToString:@"new_liker"]) {
        UIView *Badge = (UIView*)[self.view viewWithTag:selfBadgeTag+0];
        [Utils Hidden:Badge Bool:YES];
    }else{
        
    }
}
- (UITableView *)searchTableView
{
    if (!_searchTableView) {
        _searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kSearchViewHeight+kNavigationBarHeight, DeviceWidth, DeviceHeight -kSearchViewHeight-kNavigationBarHeight ) style:UITableViewStylePlain];
        _searchTableView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
        _searchTableView.delegate = self;
       _searchTableView.dataSource = self;
        _searchTableView.scrollsToTop = YES;
       _searchTableView.separatorColor = RGBA(225, 225, 225, 1);//分隔条颜色
        _searchTableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 51, 0);//滚动条偏移量
        [self.view addSubview:_searchTableView];
        _searchTableView.sectionIndexColor = RGBA(153, 153, 153, 1);//索引颜色
        _searchTableView.sectionIndexBackgroundColor = [UIColor clearColor];//索引未选中背景颜色
        _searchTableView.sectionIndexTrackingBackgroundColor = [UIColor clearColor];//索引选择背景颜色
        _searchTableView.tag = 1997;
        
//
    }
    return _searchTableView;
}
- (void)clickBackGround
{
    [self clickButtonRight];
}
-(void)viewWillAppear:(BOOL)animated
{
    UIView *Badge1 = (UIView*)[self.view viewWithTag:selfBadgeTag+1];
    UIView *Badge2 = (UIView*)[self.view viewWithTag:selfBadgeTag+0];

    if ([[Utils defaultsForKey:@"new_friend"] isEqualToString:@"YES"]) {
        [Utils Hidden:Badge1 Bool:YES];
    }else if ([[Utils defaultsForKey:@"new_liker"] isEqualToString:@"YES"]) {
        [Utils Hidden:Badge2 Bool:YES];
    }else if ([[Utils defaultsForKey:@"new_friend"] isEqualToString:@"NO"]){
        if (Badge1.alpha==1) {
            [Utils Hidden:Badge1 Bool:NO];
        }
    }else if ([[Utils defaultsForKey:@"new_liker"] isEqualToString:@"NO"]){
        if (Badge2.alpha==1) {
            [Utils Hidden:Badge2 Bool:NO];
        }
    }
     [self sortFriendsAndDisplay];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [self clickButtonRight];
}


#pragma mark  search 相关的
- (void)setSomeFrame
{
    self.searchTextField.text = @"";
    if (self.isSearchFriend) {
        self.searchTextField.returnKeyType = UIReturnKeyDefault;
        self.searchTextField.placeholder = @"请输入昵称/团员号";
        
        self.title = @"查找";
    }else{
        self.searchTextField.returnKeyType = UIReturnKeySearch;
        self.searchTextField.placeholder = @"请输入团员号";
        [AVAnalytics event:@"搜索"]; // 通知服务器一个点击事件。

        self.title = @"搜索";
    }
    [self.searchTextField becomeFirstResponder];
    self.searchTableView.hidden = NO;
    

    if ([self.friendArr count] == 0) {
        promptView.viewPrompt.frame = CGRectMake(0, 80+kNavigationBarHeight+kSearchViewHeight, DeviceWidth, DeviceHeight-80-kNavigationBarHeight-kSearchViewHeight);
        
    }
    CGRect frame = CGRectMake(0, kNavigationBarHeight+kSearchViewHeight, DeviceWidth, DeviceHeight-kNavigationBarHeight-kSearchViewHeight);
    self.tableView.frame = frame;
        searchView.hidden = NO;
}
- (void)textFieldDidChange:(UITextField *)textField
{
    //文字改变
    if(self.isSearchFriend ){
        if (textField&&textField.text.length>0) {
            NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@",textField.text];
            self.nFriendArr =[NSArray arrayWithArray: [self.searchArr filteredArrayUsingPredicate:pred]];
            [self.searchTableView reloadData];
        }else{
            self.nFriendArr= [NSArray array];
            [self.searchTableView reloadData];
        }
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    if (!self.isSearchFriend) {
        if (self.searchTextField&&self.searchTextField.text.length) {
            AVQuery *first =[MLUser query];
            [first whereKey:@"molianId" equalTo:[NSNumber numberWithInteger:[self.searchTextField.text integerValue]]];
            
            [first findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                if (!error&&objects.count) {
                    self.nFriendArr = [NSArray arrayWithArray:objects];
                    [self.searchTableView reloadData];
                }else{
                    [HUD Prompt:@"没有搜索到"];
                }
            }];
        }else{
            [HUD Prompt:@"没有搜索到"];
        }

    }else{
        //不用提示
    }
 
    return YES;
}
- (void)addSearchView
{
    searchView = [[UIView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight, DeviceWidth, kSearchViewHeight)];
    searchView.backgroundColor = RGBA(31, 30, 30, 0.99);
    UIView *borderView = [[UIView alloc] initWithFrame:CGRectMake(10,(kSearchViewHeight-30)/2, DeviceWidth-70, 30)];
    borderView.layer.cornerRadius = 5;
    borderView.layer.borderWidth = 0.5;
    borderView.layer.borderColor = [[UIColor clearColor] CGColor];
    borderView.backgroundColor = [UIColor whiteColor];
    UIImageView *seachImageView = [[UIImageView alloc] initWithFrame:CGRectMake(8, 8, 14, 14)];
    seachImageView.image = [UIImage imageNamed:@"lover_search-bar_search_icon"];
    [borderView addSubview:seachImageView];
    
    [searchView addSubview:borderView];
    self.searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(30, 0, DeviceWidth-30-70-10, 30)];
    
    
    self.searchTextField.backgroundColor = [UIColor clearColor];
    self.searchTextField.placeholder = @"请输入昵称/团员号";
    self.searchTextField.font =[UIFont fontWithName:FontName size:15];
    [self.searchTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.searchTextField setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];
    // [self.searchTextField setValue:[UIFont boldSystemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
    
    self.searchTextField.delegate = self;
    self.searchTextField.borderStyle = UITextBorderStyleNone;
    self.searchTextField.textColor = [UIColor blackColor];
    self.searchTextField.clearButtonMode = UITextFieldViewModeAlways;
    //}
    self.searchTextField.adjustsFontSizeToFitWidth = YES;
    [borderView addSubview:self.searchTextField];
    self.rightButton=[UIButton buttonWithType:UIButtonTypeCustom];
    self.rightButton.frame=CGRectMake(DeviceWidth-60, 2+(kSearchViewHeight-2-38)/2, 60, 38);
    [self.rightButton setTitle:@"取消" forState:UIControlStateNormal];
    self.rightButton.titleLabel.font = [UIFont fontWithName:FontName size:15];
    [self.rightButton setTitleColor:SelectViewClolor forState:UIControlStateNormal];
    [self.rightButton setTitleColor: [UIColor grayColor] forState:UIControlStateHighlighted];
    [self.rightButton addTarget:self action:@selector(clickButtonSearch) forControlEvents:UIControlEventTouchUpInside];
    
    [searchView addSubview:self.rightButton];
    [self.view addSubview:searchView];
    searchView.hidden = YES;
}
- (void)clickButtonSearch
{
    if ([self.rightButton.titleLabel.text isEqualToString:@"取消"]) {
        [self clickButtonRight];
    }
}

//取消的意思
- (void)clickButtonRight
{
    if ([self.friendArr count] == 0) {
        promptView.viewPrompt.frame = CGRectMake(0, 80+kNavigationBarHeight, DeviceWidth, DeviceHeight-80-kNavigationBarHeight);
    }
    self.title = @"试恋记录";
    isClick = YES;
    searchView.hidden = YES;
    self.searchTableView.hidden = YES;
    CGRect frame = CGRectMake(0, kNavigationBarHeight, DeviceWidth, DeviceHeight-kNavigationBarHeight);
    self.tableView.frame = frame;
    self.nFriendArr= [NSArray array];
    [self.searchTableView reloadData];
    [self.searchTextField resignFirstResponder];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.friendArr = [[[ShareData shareData].friends reverseObjectEnumerator] allObjects];
    if (self.friendArr == nil || self.friendArr.count == 0) {
         [self loadFriendsData];
        
        
    }
    
    isClick = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self addSearchView];
    // Do any additional setup after loading the view.
    self.title = @"试恋记录";
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"lover_add_icon"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(adduser)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cmd:) name:@"cmd" object:nil];
  
    
   // self.indexArray = @[@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z", @"#"];
   // self.groupedFriends = [[NSMutableDictionary alloc]init];
  //  self.recommendFriends = [[NSMutableArray alloc]init];
    

    
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight, DeviceWidth, DeviceHeight-kNavigationBarHeight)style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollsToTop = YES;
    self.tableView.tableFooterView = [[UIView alloc]init];
//    self.tableView.tableHeaderView = headerView;
    self.tableView.separatorColor = RGBA(225, 225, 225, 1);//分隔条颜色
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 51, 0);//滚动条偏移量
    [self.view addSubview:self.tableView];
    self.tableView.sectionIndexColor = RGBA(153, 153, 153, 1);//索引颜色
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];//索引未选中背景颜色
    self.tableView.sectionIndexTrackingBackgroundColor = [UIColor clearColor];//索引选择背景颜色
    
    _slimeView = [[SRRefreshView alloc] init];
    _slimeView.delegate = self;
    _slimeView.upInset = 0;
    _slimeView.slimeMissWhenGoingBack = YES;
    _slimeView.slime.bodyColor = APPCOLOR(1);
    _slimeView.slime.skinColor = [UIColor whiteColor];
    _slimeView.slime.lineWith = 1;
    _slimeView.slime.shadowBlur = 0;
    _slimeView.slime.shadowColor = [UIColor redColor];
    [self.tableView addSubview:self.slimeView];
    
    // TODO 监听有新好友申请的通知
    //用来加载好友关系
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadMyFriendsData) name:@"loadMyFriendsData" object:nil];
    
//    if([ShareData shareData].friends.count){
//        [self sortFriendsAndDisplay];
//    }else{
//        if([ShareData shareData].friends == nil||[ShareData shareData].friends.count == 0){
//            [self loadFriendsData];
//        }
//    }
}
// 加载好友关系(不是好友的时候,是否需要再次查询是否为好友,是否需要加为好友)
- (void)loadFriendsData {
    // 使用followee表里面用户关注的对象初始化friendsArray
     [HUD setOnViewWithTitle:@"加载中" animated:YES];
    MLUser *currentUser = [MLUser currentUser];
    AVQuery *followeeQuery = [MLUser followeeQuery:currentUser.objectId];
    [followeeQuery includeKey:@"followee"];
    followeeQuery.limit = kNumber;
    [followeeQuery orderByDescending:@"createdAt"];
    [followeeQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
         [HUD hideFromViewAnimated:YES];
        //停止加载
        [_slimeView endRefresh];
        if (!error) {
            
            // 初始化好友列表
            [ShareData shareData].friends = [NSMutableArray arrayWithArray:objects];
            self.friendArr = [[[NSArray arrayWithArray:objects] reverseObjectEnumerator] allObjects];
            NSMutableDictionary *d = [NSMutableDictionary dictionary];
            for (MLUser *u in objects) {
                [d setObject:@"YES" forKey:u.objectId];
            }
            if(objects &&objects.count == kNumber){
                // NSInteger skip = kNumber;
                [self againloadFriendsDataSkip:kNumber mDic:d];
            }
            
            [Utils savePassFriendDictionary:d];
            //请求完数据,发送通知告诉好友页面刷新数据
            [[NSNotificationCenter defaultCenter] postNotificationName:@"loadMyFriendsData" object:self userInfo:nil];
        }
    }];
}
- (void)againloadFriendsDataSkip:(NSInteger )skip mDic:(NSMutableDictionary *)mdic
{
     [HUD setOnViewWithTitle:@"加载中" animated:YES];
    MLUser *currentUser = [MLUser currentUser];
    AVQuery *followeeQuery = [MLUser followeeQuery:currentUser.objectId];
    [followeeQuery includeKey:@"followee"];
    followeeQuery.limit = kNumber;
    followeeQuery.skip = skip;
    [followeeQuery orderByDescending:@"createdAt"];
    [followeeQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
         [HUD hideFromViewAnimated:YES];
        //停止加载
        [_slimeView endRefresh];
        if (!error) {
            // 初始化好友列表
            [[ShareData shareData].friends addObjectsFromArray:objects];
            for (MLUser *u in objects) {
                [mdic setObject:@"YES" forKey:u.objectId];
            }
            if(objects &&objects.count == kNumber){
                [self againloadFriendsDataSkip:skip+kNumber mDic:mdic];
            }
            
            [Utils savePassFriendDictionary:mdic];
            //请求完数据,发送通知告诉恋人页面刷新数据
            [[NSNotificationCenter defaultCenter] postNotificationName:@"loadMyFriendsData" object:self userInfo:nil];
        }
    }];
}
- (void)dealloc
{
     [[NSNotificationCenter defaultCenter] removeObserver:self];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"cmd" object:nil];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"loadMyFriendsData" object:nil];
}
- (void)loadMyFriendsData
{
    [self sortFriendsAndDisplay];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
    // Dispose of any resources that can be recreated.
}

#pragma mark - init



// 将好友列表分类显示
- (void)sortFriendsAndDisplay {
    if ([ShareData shareData].friends.count) {
        self.friendArr = [[[ShareData shareData].friends reverseObjectEnumerator] allObjects];
    }
    
  //  [self.recommendFriends removeAllObjects];
   // [self.friendSectionTitles removeAllObjects];
  //  [self.groupedFriends removeAllObjects];
//    NSMutableArray *sectionTitles = [[NSMutableArray alloc]init];
//    
////    for (int i = 0; i<[ShareData shareData].friends.count; i++) {
////        
////    }
//    for (int i = 0; i<[ShareData shareData].friends.count; i++) {
//        MLUser *friend  =(MLUser *) ([ShareData shareData].friends[i]);
//        // 专属恋人
//        if (MLUserType_NORMAL != friend.type) {
//            [self.recommendFriends addObject:friend];
//        }else{
//            // 获取第一个字符的首字母
//            NSString *name = [friend.nickname substringToIndex:1];
//            NSString *firstLetter;
//            if ([name canBeConvertedToEncoding:NSASCIIStringEncoding]) {
//                firstLetter = [NSString stringWithFormat:@"%c", toupper([name characterAtIndex:0])];
//            } else {
//                firstLetter = [NSString stringWithFormat:@"%c", toupper([Pinyin pinyinFirstLetter:[name characterAtIndex:0]])];
//            }
//            // 添加新的索引
//            if ([sectionTitles indexOfObject:firstLetter] == NSNotFound) {
//                [sectionTitles addObject:firstLetter];
//            }
//            // 将好友按首字母分组
//            NSMutableArray *group = [self.groupedFriends objectForKey:firstLetter];
//            if (group) {
//                [group addObject:friend];
//            } else {
//                group = [NSMutableArray arrayWithObject:friend];
//                [self.groupedFriends setObject:group forKey:firstLetter];
//            }
//        }
//        
//    }
//    // 将索引列表排序, 有#将其放在队尾
//    if ([sectionTitles indexOfObject:@"#"] != NSNotFound) {
//        [sectionTitles removeObject:@"#"];
//        self.friendSectionTitles = [NSMutableArray arrayWithArray:[sectionTitles sortedArrayUsingSelector:@selector(compare:)]];
//        [self.friendSectionTitles addObject:@"#"];
//    } else {
//        self.friendSectionTitles = [NSMutableArray arrayWithArray:[sectionTitles sortedArrayUsingSelector:@selector(compare:)]];
//    }
//    
//    // 第一行放专属恋人
//    if ([self.recommendFriends count]) {
//        [self.friendSectionTitles insertObject:@"专属恋人" atIndex:0];
//    }
//    [self.tableView reloadData];
//    
    if (!promptView) {
        promptView = [[Utils alloc]init];
        
        [promptView viewControllerPrompt:CGRectMake(0, 80+kNavigationBarHeight, DeviceWidth, DeviceHeight-80-kNavigationBarHeight) Text:@"还没有试恋过" Image:[UIImage imageNamed:@"lianren_nul"]];
        [self.view insertSubview:promptView.viewPrompt belowSubview:self.tableView];
    }
    
    
    if ([self.friendArr count] == 0) {
        promptView.viewPrompt.hidden = NO;
    }else{
        promptView.viewPrompt.hidden = YES;
    }
    
    [self.tableView reloadData];
    
}


#pragma mark - tableview delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static  NSString *CellIdentifier = @"FriendCell";
    FriendCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if  (cell == nil) {
        cell = [[FriendCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        
    }
    // 专属恋人的屌丝
    MLUser *user;
    if (tableView.tag == 1997) {
        if (self.nFriendArr.count) {
            
            if (self.isSearchFriend) {
                user = [self.searchDic objectForKey:self.nFriendArr[indexPath.row]];
            }else{
                user = self.nFriendArr[indexPath.row];
            }
            
            
            cell.nameLabel.text = user.nickname;
           // [cell.avatarImgView sd_setImageWithURL:[NSURL URLWithString:user.avatar.url] placeholderImage:[UIImage imageWithColor:[UIColor whiteColor]]];
            if (!user.subAvatar || [user.subAvatar isEqualToString:@""]) {
                [cell.avatarImgView sd_setImageWithURL:[NSURL URLWithString:user.avatar.url] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
                
            }else{
                [cell.avatarImgView sd_setImageWithURL:[NSURL URLWithString:user.subAvatar] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
            }
            [cell.ageLabel setTitle:[NSString stringWithFormat:@"%ld", (long)[user getUserAge]] forState:UIControlStateNormal];
            if (MLUserGender_MALE == user.gender) {
                [cell.ageLabel setBackgroundImage:[UIImage imageNamed:@"boy_age"] forState:UIControlStateNormal];
            } else {
                [cell.ageLabel setBackgroundImage:[UIImage imageNamed:@"girl_age"] forState:UIControlStateNormal];
            }
            cell.locationLabel.text = user.selectCity;
            return cell;
        }else{
            return nil;
        }
    
    }else{
//            if (indexPath.section == 0 && [self.recommendFriends count]) {
//                user = self.recommendFriends[indexPath.row];
//            } else {
//                NSString *firstLetter = [self.friendSectionTitles objectAtIndex:indexPath.section];
//                NSMutableArray *group = [self.groupedFriends objectForKey:firstLetter];
//                user = [group objectAtIndex:indexPath.row];
//            }
        user = [self.friendArr objectAtIndex:indexPath.row];
        cell.nameLabel.text = user.nickname;
        //[cell.avatarImgView sd_setImageWithURL:[NSURL URLWithString:user.avatar.url] placeholderImage:[UIImage imageWithColor:[UIColor whiteColor]]];
        if (!user.subAvatar || [user.subAvatar isEqualToString:@""]) {
            [cell.avatarImgView sd_setImageWithURL:[NSURL URLWithString:user.avatar.url] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
            
        }else{
            [cell.avatarImgView sd_setImageWithURL:[NSURL URLWithString:user.subAvatar] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
        }
        [cell.ageLabel setTitle:[NSString stringWithFormat:@"%ld", (long)[user getUserAge]] forState:UIControlStateNormal];
        if (MLUserGender_MALE == user.gender) {
            [cell.ageLabel setBackgroundImage:[UIImage imageNamed:@"boy_age"] forState:UIControlStateNormal];
        } else {
            [cell.ageLabel setBackgroundImage:[UIImage imageNamed:@"girl_age"] forState:UIControlStateNormal];
        }
        cell.locationLabel.text = user.selectCity;
        
        return  cell;

    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MLUser *showUser;
    if (tableView.tag == 1997) {
        if (self.isSearchFriend) {
             showUser = [self.searchDic objectForKey:self.nFriendArr[indexPath.row]];
        }else{
             showUser = self.nFriendArr[indexPath.row];
        }
    }else{
        
        showUser = self.friendArr [indexPath.row];
//            if (indexPath.section == 0 && [self.recommendFriends count]) {
//                showUser = self.recommendFriends[indexPath.row];
//            }else{
//                NSString *firstLetter = [self.friendSectionTitles objectAtIndex:indexPath.section];
//                NSMutableArray *group = [self.groupedFriends objectForKey:firstLetter];
//                showUser = [group objectAtIndex:indexPath.row];
//            }
        }
    MLUserDataViewController *userInfoVC = [[MLUserDataViewController alloc]init];
    userInfoVC.userData = showUser;
    userInfoVC.isLovein = YES;
   
    [Utils pushTabbarHidden:userInfoVC Selfvc:self];
    
    
}

//section个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView.tag == 1997) {
        return 1;
    }else{
        return 1;
        // TODO 加上专属恋人
//        return [self.friendSectionTitles count];
    }
    
}

//cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (tableView.tag == 1997) {
        
        return self.nFriendArr.count;
    }else {
        return self.friendArr.count;
        
//            // 专属恋人
//            if ([self.recommendFriends count] && (section == 0)) {
//                return [self.recommendFriends count];
//            }
//        // 首字母
//        NSString *firstLetter = [self.friendSectionTitles objectAtIndex:section];
//        NSMutableArray *group = [self.groupedFriends objectForKey:firstLetter];
//            return [group count];
    }
    
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    
    if (tableView.tag ==  1997) {
        return nil;
    }else{
         return nil;
    }
   
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    if (tableView.tag == 1997) {
        return 0;
    }else{
        return 0;
//        return [self.friendSectionTitles indexOfObject:title];
    }
    
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (tableView.tag == 1997) {
        return nil;
    }else{
        return nil;
//        return [self.friendSectionTitles objectAtIndex:section];
    }
    
}


- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (tableView.tag == 1997) {
        return nil;
    }else{
        return nil;
//        UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 20)];
//        headerLabel.backgroundColor =[[UIColor grayColor] colorWithAlphaComponent:0];
//        headerLabel.text = [NSString stringWithFormat:@"   %@",[self.friendSectionTitles objectAtIndex:section]];
//        headerLabel.font = [UIFont fontWithName:FontName size:14];
//        headerLabel.textColor = [UIColor grayColor];
//        headerLabel.backgroundColor = RGBA(249, 249, 249, 1);
//        return headerLabel;

    }
    
}


//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 56;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView.tag == 1997) {
        return 0;
    }else{
        // 每个cell的头部间距
        return 0;
    }
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
{
    //每个cell的底部间距
    return 0.00001;
}

//#pragma mark - searchBar delegate
//- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
//    [searchBar resignFirstResponder];
//}
//
//- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
//    [searchBar resignFirstResponder];
//}
//
//- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
//    return YES;
//}
//
//- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
//    return YES;
//}

#pragma mark - user interaction

-(void)search
{
    if (isClick) {
        [_rightButton setTitle:@"取消" forState:UIControlStateNormal];
        self.isSearchFriend = YES;
        NSMutableArray *arr = [NSMutableArray array];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        for (MLUser *u in [ShareData shareData].friends) {
            NSString *str = [NSString stringWithFormat:@"%@%ld",u.nickname,(long)u.molianId];
            [arr addObject:str];
            [dic setValue:u forKey:str];
        }
        self.searchArr = [NSArray arrayWithArray:arr];
        self.searchDic = [NSDictionary dictionaryWithDictionary:dic];
        [self setSomeFrame];
        isClick = NO;
    }else{
        [self clickButtonRight];
    }
}

-(void)adduser
{
    if (isClick) {
        self.isSearchFriend = NO;
        [self setSomeFrame];
        isClick = NO;
    }else{
        [self clickButtonRight];
    }
   
    //_adduservc = [[AddUser alloc]initWithController:self];

}
// 跳转到处理喜欢我的人页面
- (void)likeMeAction {
    [AVAnalytics event:@"喜欢我的页面访问"]; // 通知服务器一个点击事件。
    UIView *tabBadge = (UIView*)[self.tabBarController.tabBar viewWithTag:100002];
    [Utils Hidden:tabBadge Bool:NO];
    [Utils saveToDefaults:@"NO" forKey:@"new_liker"];
    UIView *Badge = (UIView*)[self.view viewWithTag:selfBadgeTag+0];
    if ((Badge.alpha == 1)) {
        [Utils Hidden:Badge Bool:NO];
    }
    LikeMeViewController *likeMeController = [[LikeMeViewController alloc]init];
   // likeMeController.likeMeList = self.likeMeList;
    [Utils pushTabbarHidden:likeMeController Selfvc:self];
}

// 跳转到好友申请页面
- (void)friendApplyAction {
    UIView *tabBadge = (UIView*)[self.tabBarController.tabBar viewWithTag:100002];
    [Utils Hidden:tabBadge Bool:NO];
    
    [Utils saveToDefaults:@"NO" forKey:@"new_friend"];
    UIView *Badge = (UIView*)[self.view viewWithTag:selfBadgeTag+1];
    if ((Badge.alpha == 1)) {
        [Utils Hidden:Badge Bool:NO];
    }
    FriendApplyViewController *friendApplyController = [[FriendApplyViewController alloc]init];
 //   friendApplyController.friendApplyList = self.friendApplyList;
    [Utils pushTabbarHidden:friendApplyController Selfvc:self];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (_slimeView) {
        [_slimeView scrollViewDidScroll];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
  
    if (_slimeView) {
        [_slimeView scrollViewDidEndDraging];
    }
}
- (void)slimeRefreshStartRefresh:(SRRefreshView *)refreshView
{
    [self loadFriendsData];
}
@end
